<template>
    <div class="upload-data-source-modal">
        <n-button type="primary" @click="showModal = true">
            上传数据源
        </n-button>
        <n-modal
            v-model:show="showModal"
            @after-leave="afterLeave"
        >
            <n-card
                style="width: 600px"
                title="新增数据源"
                :bordered="false"
                size="huge"
                role="dialog"
                aria-modal="true"
            >
                <n-form
                    ref="formRef"
                    :model="newDataSource"
                    :rules="rules"
                    label-placement="left"
                    label-width="auto"
                    require-mark-placement="right-hanging"
                    size="medium"
                    :style="{
                    maxWidth: '640px'
                }"
                >
                    <n-form-item label="文件名称" path="name">
                        <n-input v-model:value="newDataSource.name" type="text" placeholder="文件名称"/>
                    </n-form-item>
                    <n-form-item label="数据源类型" path="dataSourceType">
                        <n-radio-group v-model:value="newDataSource.data_source_type" name="radioGroup">
                            <n-space>
                                <n-radio
                                    v-for="song in dataSourceTypeSongs"
                                    :key="song.value"
                                    :value="song.value">
                                    {{ song.label }}
                                </n-radio>
                            </n-space>
                        </n-radio-group>
                    </n-form-item>
                    <n-form-item label="二级名称" path="category">
                        <div>
                            <n-select
                                style="width: 200px"
                                v-model:value="newDataSource.category"
                                :options="categoryList"
                                placeholder="二级文件夹"/>
                            <n-input v-show="newDataSource.category===false"
                                     v-model:value="newDataSource.categoryCustom" type="text" placeholder="二级名称"/>
                        </div>

                    </n-form-item>
                    <n-form-item label="上传数据源" path="file">
                        <n-upload
                            ref="uploadRef"
                            :action="app.ip+'super_admin/data_source'"
                            :method="state.apiMethod"
                            :headers="{token: user.getToken}"
                            :data="newDataSourceComputed"
                            :default-upload="false"
                            v-model:default-file-list="fileListRef"
                            :max="1"
                            @change="handleChange"
                            @error="error"
                            @finish="handleFinish"
                        >
                            <n-button>上传文件</n-button>
                        </n-upload>
                    </n-form-item>
                    <n-form-item label="Web地址" path="web_url" v-show="newDataSource.data_source_type==='web'">
                        <n-input v-model:value="newDataSource.web_url" type="text" placeholder="Web地址"/>
                    </n-form-item>
                    <div style="display: flex; justify-content: flex-end">
                        <n-button @click="onNegativeClick">
                            取消
                        </n-button>
                        <n-button type="primary" @click="handleValidateButtonClick">
                            确定
                        </n-button>
                    </div>
                </n-form>
            </n-card>
        </n-modal>
    </div>
</template>

<script setup>
import {useAppStore} from "@/stores/app";
import {useUserStore} from "@/stores/user";
import workApi from "@/http/workApi";
import {useSuperAdminStore} from "@/stores/superAdmin";

const props = defineProps(['setKey'])
const app = useAppStore()
const user = useUserStore()
const uploadRef = ref(null)
const showModal = ref(false)
const superAdmin = useSuperAdminStore()
// 二级列表
const categoryList = computed(() => {
    let a = superAdmin.dataSource.enable
    let list = []
    for (let i of a) {
        list.push(i.category)
    }
    list = Array.from(new Set(list)) // 去重
    let b = [{label: "自定义", value: false}]
    for (let i of list) {
        b.push({label: i, value: i})
    }
    console.log(b)
    return b
})

// 状态
const state = reactive({
    type: 'add',
    apiMethod: 'post',
})
// 数据类型枚举
const dataSourceTypeSongs = [
    {label: '文件', value: 'file'},
    {label: 'API', value: 'api'},
    {label: '网页', value: 'web'},
    {label: '数据库', value: 'database'},
]
const newDataSource = ref({
    name: null,
    data_source_type: 'file',
    category: null,
    categoryCustom: null,
    web_url: '',
})
const newDataSourceComputed = computed(() => {
    let a = {...newDataSource.value}
    if (!a.category) {
        a.category = a.categoryCustom
    }
    return a
})
// 验证规则
const rules = {
    name: {
        required: true,
        trigger: ['blur'],
        message: '未填'
    },
    category: {
        required: true,
        validator() {
            if (!!newDataSource.value.category) {
                return true
            }
            return newDataSource.value.category === false && !!newDataSource.value.categoryCustom;

        },
        trigger: ['blur'],
        message: '未填'
    },
    file: {
        required: true,
        validator() {
            if (fileListLengthRef.value === {}) {
                return !!fileListLengthRef.value;
            }
        },
        trigger: ['blur'],
        message: '未填'
    },
    web_url: {
        required: true,
        validator(rule, value) {
            return newDataSource.value.data_source_type !== 'web' || !!value
        },
        trigger: ['blur'],
        message: '未填'
    }

};
const formRef = ref(null);
const fileListLengthRef = ref(0)
const handleChange = (options) => {
    newDataSource.value.name = options.file.name.split(".")[0]
    // 文件添加成功更新文件列表长度
    fileListLengthRef.value = options.fileList.length;
}
const handleClick = () => {
    // 上传文件
    uploadRef.value?.submit()
}
const handleFinish = ({event}) => {
    let response = JSON.parse(event.target.response)
    console.log(response)
    window.$message[response.tip.type](response.tip.info)
    // 文件上传成功
    onNegativeClick() // 关闭模态框
}

function error({event}) {
    console.log(event)
}
// 文件上传列表
const fileListRef = ref([])
const onNegativeClick = () => {
    superAdmin.updateDataSource()
    // 关闭模态框
    showModal.value = false

}
const afterLeave = () => {
    // 关闭模态框后的回调函数
    props.setKey()
}
const handleValidateButtonClick = () => {
    console.log(fileListRef.value)
    console.log(fileListLengthRef.value)
    // 点击确定
    // 验证是否填写
    formRef.value?.validate((errors) => {
        if (!errors) {
            // 是否修改并且更新文件
            if (state.type === 'modify' && !fileListLengthRef.value) {
                let forms = new FormData()
                forms.append("id", newDataSource.value.id)
                forms.append("name", newDataSource.value.name)
                forms.append("data_source_type", newDataSource.value.data_source_type)
                forms.append("category", newDataSource.value.category||newDataSource.value.categoryCustom)
                forms.append("categoryCustom", newDataSource.value.categoryCustom)
                if (newDataSource.value.web_url !== undefined) {
                    forms.append("web_url", newDataSource.value.web_url);
                }
                workApi({
                    method: 'put',
                    url: 'super_admin/data_source',
                    headers: {'content-type': 'application/x-www-form-urlencoded'},
                    data: forms
                }).then(()=>{
                    onNegativeClick()
                })
            } else {
                handleClick()
            }
        } else {
            window.$message.error('验证失败')
        }
    })
}

// 父组件打开
const setDataSource = (value) => {
    newDataSource.value = {...value}
    state.type = 'modify'
    state.apiMethod = 'put'
    if ('url' in newDataSource.value) {
        fileListRef.value.push({
            id: newDataSource.value.name,
            name: newDataSource.value.name,
            url: newDataSource.value.url,
            status: 'finished'
        })
    }
    showModal.value = true;
}
defineExpose({
    setDataSource
})
</script>

<style scoped lang="less">
.n-button {
    margin: 15px 0;
}
</style>